package org.ysling.litemall.db.service;
// Copyright (c) [ysling] [927069313@qq.com]
// [litemall-plus] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//             http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
import com.github.pagehelper.PageHelper;
import org.ysling.litemall.db.dao.LitemallCartMapper;
import org.ysling.litemall.db.domain.LitemallBrand;
import org.ysling.litemall.db.domain.LitemallCart;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.ysling.litemall.db.domain.LitemallGrouponRules;
import org.ysling.litemall.db.example.LitemallCartExample;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
@CacheConfig(cacheNames = "cart")
public class LitemallCartService {

    @Resource
    private LitemallCartMapper cartMapper;

    @Cacheable(sync = true)
    public LitemallCart queryExist(Integer goodsId, Integer productId, Integer userId) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andGoodsIdEqualTo(goodsId).andProductIdEqualTo(productId).andUserIdEqualTo(userId).andDeletedEqualTo(false);
        return cartMapper.selectOneByExample(example);
    }

    @CacheEvict(allEntries = true)
    public void add(LitemallCart cart) {
        cart.setAddTime(LocalDateTime.now());
        cart.setUpdateTime(LocalDateTime.now());
        cartMapper.insertSelective(cart);
    }

    @CacheEvict(allEntries = true)
    public int updateById(LitemallCart cart) {
        cart.setUpdateTime(LocalDateTime.now());
        return cartMapper.updateByPrimaryKeySelective(cart);
    }

    @CacheEvict(allEntries = true)
    public int updateVersionSelective(LitemallCart cart) {
        cart.setUpdateTime(LocalDateTime.now());
        return cartMapper.updateWithVersionByPrimaryKeySelective(cart.getVersion(), cart);
    }

    @Cacheable(sync = true)
    public List<LitemallCart> queryByUid(int userId) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        return cartMapper.selectByExample(example);
    }


    @Cacheable(sync = true)
    public List<LitemallCart> queryByUidAndChecked(Integer userId) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andUserIdEqualTo(userId).andCheckedEqualTo(true).andDeletedEqualTo(false);
        return cartMapper.selectByExample(example);
    }

    @CacheEvict(allEntries = true)
    public int delete(List<Integer> productIdList, int userId) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andUserIdEqualTo(userId).andProductIdIn(productIdList);
        return cartMapper.logicalDeleteByExample(example);
    }

    @Cacheable(sync = true)
    public LitemallCart findById(Integer id) {
        return cartMapper.selectByPrimaryKey(id);
    }

    @Cacheable(sync = true)
    public LitemallCart findById(Integer userId, Integer id) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andUserIdEqualTo(userId).andIdEqualTo(id).andDeletedEqualTo(false);
        return cartMapper.selectOneByExample(example);
    }

    @CacheEvict(allEntries = true)
    public int updateCheck(Integer userId, List<Integer> idsList, Boolean checked) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andUserIdEqualTo(userId).andProductIdIn(idsList).andDeletedEqualTo(false);
        LitemallCart cart = new LitemallCart();
        cart.setChecked(checked);
        cart.setUpdateTime(LocalDateTime.now());
        return cartMapper.updateByExampleSelective(cart, example);
    }

    @CacheEvict(allEntries = true)
    public void clearGoods(Integer userId) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andUserIdEqualTo(userId).andCheckedEqualTo(true);
        LitemallCart cart = new LitemallCart();
        cart.setDeleted(true);
        cartMapper.updateByExampleSelective(cart, example);
    }

    @Cacheable(sync = true)
    public List<LitemallCart> querySelective(Integer userId, Integer goodsId, Integer page, Integer limit, String sort, String order) {
        LitemallCartExample example = new LitemallCartExample();
        LitemallCartExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);

        if (!Objects.isNull(userId)) {
            criteria.andUserIdEqualTo(userId);
        }
        if (!Objects.isNull(goodsId)) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        if (StringUtils.hasText(sort) && StringUtils.hasText(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, limit);
        return cartMapper.selectByExample(example);
    }

    @CacheEvict(allEntries = true)
    public int deleteById(Integer id) {
        return cartMapper.logicalDeleteByPrimaryKey(id);
    }

    @Cacheable(sync = true)
    public boolean checkExist(Integer goodsId) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andGoodsIdEqualTo(goodsId).andCheckedEqualTo(true).andDeletedEqualTo(false);
        return cartMapper.countByExample(example) != 0;
    }

    @CacheEvict(allEntries = true)
    public void updateProduct(Integer id, String goodsSn, String goodsName, BigDecimal price, String url) {
        LitemallCart cart = new LitemallCart();
        cart.setPrice(price);
        cart.setPicUrl(url);
        cart.setGoodsSn(goodsSn);
        cart.setGoodsName(goodsName);
        LitemallCartExample example = new LitemallCartExample();
        example.or().andProductIdEqualTo(id);
        cartMapper.updateByExampleSelective(cart, example);
    }

    /**
     * 计算购物车商品金额
     * @param grouponPrice
     * @param grouponRules
     * @param checkedGoodsList
     * @param checkedGoodsPrice
     * @return
     */
    public static BigDecimal getBigDecimal(BigDecimal grouponPrice, LitemallGrouponRules grouponRules, List<LitemallCart> checkedGoodsList, BigDecimal checkedGoodsPrice) {
        for (LitemallCart checkGoods : checkedGoodsList) {
            //  只有当团购规格商品ID符合才进行团购优惠
            if (grouponRules != null && grouponRules.getGoodsId().equals(checkGoods.getGoodsId())) {
                checkedGoodsPrice = checkedGoodsPrice.add(checkGoods.getPrice().subtract(grouponPrice).multiply(
                        new BigDecimal(checkGoods.getNumber())));
            } else {
                checkedGoodsPrice = checkedGoodsPrice.add(checkGoods.getPrice().multiply(
                        new BigDecimal(checkGoods.getNumber())));
            }
        }
        return checkedGoodsPrice;
    }
}
